<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @abstract 递4方请求接口 4px
 * @author zxj
 */
date_default_timezone_set('PRC');
class RepairOrder extends CI_Controller
{
    private $getData; //得到数据

    function __construct()
    {
        parent::__construct();
        $this->getData = gp();
        if ($this->getData) {
            log_output($this->getData); //将数据写入日志
        }
        //第四方登录验证
        $this->userSigna($this->getData['user'], $this->getData['key']);
        //加载模型
        $this->load->model('order_model');
        $this->load->model('product_model');
    }


    /**
     * 验证是否登录
     * @param string $user 用户名
     * @param string $key 密码
     * @return mixed
     */
    function userSigna($user = '', $key = '')
    {
        //输出数据结构
        $where = array('account' => $user, 'password' => md5($key));
        if (!$user or !$key) {
            json_output('', 'User not exist.', false);
        } else {
            $userFirst = $this->common_model->selectFirst('user', $where);
            if (!$userFirst) {
                json_output(array('userFirst' => $userFirst, 'key' => $key, 'user' => $user), '帐号密码错误.', false);
            }
        }
        return true;
    }


    /**
     * es  david  order
     */
    public function addOrder(){
        $orders = json_decode($this->getData['orders'],true);
        if (!$orders) {
            json_output('', 'Create order data can not be empty!', false);
        }
        if (!$orders['products_list'] || !is_array($orders['products_list'])) {
            json_output('', 'Create product data can not be empty!', false);
        }
        //创建订单
        $repair_point = strtolower($orders['repair_point']); //维修站点
        if (!$repair_point) {
            json_output('', 'field repair_point NOT NULL', false);
        }
        $repairSite = $this->order_model->selectFirst('mt_repair_site', array('site_prefix' => $repair_point));
        $orderData['repair_site_id'] = $repairSite['id']; //维修站点
        $orderData['source_site_id'] = $orders['source_site_id'];  //12=www.flowrepair.es
        $oid = $this->order_model->createRepairId($orderData['repair_site_id']);
        if (!$oid) {
            json_output('', 'Generate maintenance number failed,error:'.$repair_point, false);
        }
        $orderData['maintain_id'] = $oid;
        $orderData['status_id'] = 1; //订单状态,默认是1
        $orderData['maintain_type_id'] = $orders['repair_type']; //维修类型
        $orderData['source_int_id'] = $orders['reference_order_number']; //来源单号  source_order

        /*
        //website_origin
        $data['originList'] = array(
            '1'=>'pandaClever','2'=>'valukect','3'=>'rakuten','4'=>'pandawill',
            '5'=>'elephone','6'=>'aliexpress','7'=>'carrefour','8'=>'zopo',
            '9'=>'morefine','10'=>'freefeet','11'=>'geekvida_es','12'=>'geekvida_pt'
        );
        */

        $orderData['website_origin'] = $orders['website_origin']; //来源网站
        $orderData['account_origin'] = $orders['account_origin']; //来源帐号
        $orderData['source_id'] = $orders['source_id_order']; //Third party order_id 第三方单号

        /*
        $orderFirst = $this->common_model->selectFirst('maintain_order',array('source_id'=>$orders['source_ae_order']));
        if($orderFirst){
            json_output(array('oid'=>$orderFirst['maintain_id']), 'Return current order', true);
        }
        */

        $orderData['consumer_name'] = $orders['customer_name']; //客户名称
        $orderData['consumer_phone'] = $orders['customer_phone']; //客户电话
        $orderData['consumer_email'] = $orders['customer_email']; //客户邮箱

        //收件地址一般和送件地址相同，修好再寄回去
        $orderData['pickup_service'] = $orders['pickup_service']; //收件方式 0否 1是
        $orderData['pickup_address'] = $orders['pickup_address']; //收件地址
        $orderData['delivery_service'] = $orders['delivery_service']; //送件方式 0否 1是
        $orderData['delivery_address'] = $orders['delivery_address']; //送件地址
        //----待删除
        $orderData['consumer_address'] = $orders['delivery_address']; //客户地址

        $orderData['add_user'] = $this->getData['user']; //添加人
        $orderData['add_time'] = date('Y-m-d H:i:s'); //添加时间
        $this->order_model->addOrSetOrder($orderData);

        //添加产品
        $products = $orders['products_list'];
        $productData['maintain_id'] = $oid;

        $productData['sort_id'] = $products['products_sort']?$products['products_sort']:1;

        $productData['brand_id'] = $products['products_brand_id'];
        $productData['product_model'] = $products['products_model'];
        $productData['source_product_id'] = $products['products_id'];
        $productData['brand_name'] = $products['products_brand_name'];
        $productData['imei'] = $products['imei'];
        //http://flowrepair.es/new/media/tickets/PHOTO_FILE_NAME
        $productData['photos'] = serialize($products['photos']);
        $productData['video'] = $products['video'];
        $productData['size'] = $products['size'];
        $productData['color'] = $products['color'];
        $productData['is_bluetooth'] = $products['is_bluetooth'];
        $productData['is_yaokong'] = $products['is_remote_control'];
        $productData['remark_customer'] = $products['remark_customer'];
        $this->product_model->addOrSetProduct($productData);
        json_output(array('oid'=>$oid), 'Create order success', true);
    }


    /**
     * 创建订单新接口
     */
    function create_order_new(){
        $orders = json_decode($this->getData['orders'],true);
        $products = $orders['products_list'];
        if (!$orders) {
            json_output('', 'Create order data can not be empty!', false);
        }
        if (!$products || !is_array($products)) {
            json_output('', 'Create product data can not be empty!', false);
        }
        $point = strtolower($orders['repair_point']);
        $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('point' => $point));
        if (!$point) {
            json_output('', 'Didn\'t find this site', false);
        }
        $orderNum = build_order_no();
        $orderData['order_num'] = $orderNum;
        $orderData['website_origin'] =  $orders['website_origin'];
        $orderData['service_center'] = $serviceCenter['id'];
        $orderData['currency_code'] = $serviceCenter['currency'];
        $orderData['source_site'] = $orders['source_site_id'];

        $orderData['service_type'] = $orders['repair_type'];
        $orderData['product_quantity'] = $orders['quantity']?$orders['quantity']:count($products);
        $orderData['rework_orderNum'] = $orders['rework_orderNum'];
        $orderData['consumer_name'] = $orders['customer_name'];
        $orderData['consumer_phone'] = $orders['customer_phone'];
        $orderData['consumer_email'] = $orders['customer_email'];
        $orderData['storeOrShip'] = $orders['storeOrShip'];
        $orderData['remark'] = $orders['remark'];

        $orderData['consumer_type'] = $orders['consumer_type']?$orders['consumer_type']:'repair';
        $orderData['consumer_address'] = $orders['consumer_address'];
        if(!$orders['consumer_address']){
            $orderData['consumer_address'] = $orders['delivery_address'];
        }
        $orderData['shipinTrack'] = $orders['shipinTrack'];
        $orderData['pickup_service'] = $orders['pickup_service'];
        $orderData['pickup_address'] = $orders['pickup_address'];
        $orderData['delivery_service'] = $orders['delivery_service'];
        $orderData['delivery_address'] = $orders['delivery_address'];

        $orderData['delivery_country'] = $orders['delivery_country'];
        $orderData['delivery_city'] = $orders['delivery_city'];
        $orderData['delivery_state'] = $orders['delivery_state'];
        $orderData['delivery_street_address'] = $orders['delivery_street_address'];
        $orderData['delivery_zipcode'] = $orders['delivery_zipcode'];

        $merchantNum = (int)$orders['merchant_num'];
        $orderData['merchant_num'] = $merchantNum;
        $merchantFirst = $this->common_model->selectFirst('mt_customers',array('id'=>$merchantNum));
        if(!$merchantFirst){
            $consumerFirst = $this->common_model->selectFirst('mt_customers', array('email' => $orderData['consumer_email']));
            if ($consumerFirst) {
                $orderData['consumer_num'] = $consumerFirst['id'];
            }else{
                $consumerData = array(
                    'name'=>$orderData['consumer_name'],
                    'email'=>$orderData['consumer_email'],
                    'tel'=>$orderData['consumer_phone'],'type'=>3,
                    'CurrencyIsoCode'=>$serviceCenter['currency_code']
                );
                $orderData['consumer_num'] = $this->common_model->insert('mt_customers',$consumerData);
            }
        }
        $orderData['create_time'] = $orders['create_time'];
        $orderData['add_time'] = time();
        $orderData['add_user'] = $this->getData['user'];
        if($orders['reference_order_number']){
            $orderData['source_oid'] =  $orders['reference_order_number'];
        }else{
            $orderData['source_oid'] = uniqid('OM');
        }
        $oid = $this->common_model->insert('mt_order',$orderData);
        if(!$oid){
            json_output($orderData,'Failed to create the order',false);
        }
        //add product
        $productData = array();
        $productData['oid'] = $oid;
        $productData['order_num'] = $orderNum;
        $pids = array();
        foreach ($products as $rs) {
            $productData['category_id'] = $rs['category']?$rs['category']:1;
            $productData['productSku'] = $rs['productSku'];
            $productData['source_id_order'] =  $rs['source_id_order'];
            $productData['quantity'] = $rs['quantity']?intval($rs['quantity']):1;
            $productData['product_brand'] = $rs['product_brand'];
            $productData['product_model'] = $rs['product_model'];
            $productData['customerRemark'] = $rs['remark_customer'];
            $productData['defectDes'] = $rs['defectDes'];
            $productData['imei'] = $rs['imei'];
            $productData['brandCustomerNum'] = $rs['brandCustomerNum'];
            $productData['photos1'] = $rs['photo1'];
            $productData['photos2'] = $rs['photo2'];
            $productData['photos3'] = $rs['photo3'];
            $productData['photos4'] = $rs['photo4'];
            $productData['photos5'] = $rs['photo5'];
            $productData['photos6'] = $rs['photo6'];
            $productData['videoUrl'] = $rs['video'];
            $productData['create_time'] = $orders['create_time'];
            $productData['add_time'] = time();
            $productData['add_user'] = 'system';
            $pids[] = $this->common_model->insert('mt_product',$productData);
        }
        json_output(array('oid' => $orderNum, 'pids' => $pids), 'Create order successfully', true);
    }



    /**
     * 创建订单
     */
    function create_order()
    {
        //接受订单数据
        $orders = json_decode($this->getData['order'], true);
        if (!$orders) {
            json_output('', '未接收到订单数据', false);
        }
        if (!$orders['products_list'] || !is_array($orders['products_list'])) {
            json_output('', '未接收到产品数据', false);
        }
        //创建订单
        $repair_point = strtolower($orders['repair_point']); //维修站点
        if (!$repair_point) {
            json_output('', '维修站点不能为空', false);
        }
        if($repair_point == 'gb')$repair_point = 'uk';
        $repairSite = $this->order_model->selectFirst('mt_repair_site', array('site_prefix' => $repair_point));
        $orderData['repair_site_id'] = $repairSite['id']; //维修站点
        $orderData['source_site_id'] = 8;  //来源站点
        $oid = $this->order_model->createRepairId($orderData['repair_site_id']);
        if (!$oid) {
            json_output('', '生成维修单号失败,error:'.$repair_point.'无法生成单号', false);
        }
        $orderData['maintain_id'] = $oid;
        $orderData['status_id'] = 1; //订单状态,默认是1
        $orderData['source_int_id'] = $orders['reference_order_number']; //来源单号
        if (!$orderData['source_int_id']) {
            json_output('', '来源单号不能为空', false);
        }
        $orderData['consumer_name'] = $orders['customer_name']?$orders['customer_name']:$this->getData['user']; //客户名称
        $orderData['consumer_phone'] = $orders['customer_phone']?$orders['customer_phone']:'0755-23508000'; //客户电话
        $orderData['consumer_email'] = $orders['customer_email']?$orders['customer_email']:'marketing@4px.com'; //客户邮箱
        $orderData['consumer_address'] = $orders['customer_address']?$orders['customer_address']:'深圳市宝安区西乡宝源路财富港大厦D座25楼'; //客户地址
        $orderData['door_to_door_pickup'] = $orders['pick_up_service'] == 'N' ? '0' : 1; //上门取件 0否 1是
        $orderData['fault_description'] = $orders['comment'];
        if($orders['price_type']=='A'){
            $orderData['price_type'] = '0';
        }elseif($orders['price_type']=='B'){
            $orderData['price_type'] = '1';
        }
        $orderData['add_user'] = $this->getData['user']; //添加人
        $orderData['add_time'] = date('Y-m-d H:i:s'); //添加时间
        $orderData['maintain_type_id'] = 9; //第四方维修类型
        $this->order_model->addOrSetOrder($orderData);

        //添加产品
        $productList = $orders['products_list'];
        if(!$productList || !is_array($productList)){
            json_output('', '产品为空或不是数组', false);
        }
        $productInfo['maintain_id'] = $oid;
        foreach ($productList as $rs) {
            if(!$rs || !is_array($rs))continue;
            $productInfo['sort_id'] = $rs['products_sort']?$rs['products_sort']:1;
            $productInfo['brand_id'] = $rs['products_brand_id'];
            $productInfo['brand_name'] = $rs['products_brand_name'];
            $productInfo['product_model'] = $rs['products_model'];
            $productInfo['source_product_id'] = $rs['products_id'];
            $productInfo['imei'] = $rs['imei'];
            $productInfo['size'] = $rs['size'];
            $productInfo['color'] = $rs['color'];
            $productInfo['is_bluetooth'] = $rs['is_bluetooth'];
            $productInfo['is_yaokong'] = $rs['is_remote_control'];
            $this->product_model->addOrSetProduct($productInfo);
        }
        json_output('', '创建成功', true);

    }


    /***
     * 接受报价单数据
     */
    function get_priceList()
    {
        $orders = json_decode($this->getData['order'], true);
        $productList = $orders['products_list'];
        $oid = $orders['maintain_order_id'];
        if (!$oid or !$productList) {
            json_output('', '订单数据或产品数据为空', false);
        }
        foreach ($productList as $rs) {
            $is_accept_price = $rs['accepted'] == 'Yes' ? 1 : 0;
            $setData = array('is_accept_price' => $is_accept_price);
            $where = array('source_product_id' => $rs['products_id'], 'oid' => $oid);
            $this->common_model->update('maintain_product_price', $setData, $where);
        }
        json_output('', '接受数据成功!', true);

    }

    /**
     * 是否同意报价
     *
     */
    //function is_acc




}
